package com.des1gn.config;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class NettyInitalizer  extends ChannelInitializer<SocketChannel> {

    private NettyHandler nettyHandler;

    private JsonDecode jsonDecode;

    private JsonEncode jsonEncode;

    @Autowired
    public NettyInitalizer(NettyHandler nettyHandler,JsonDecode jsonDecode,JsonEncode jsonEncode){
        this.nettyHandler = nettyHandler;
        this.jsonDecode = jsonDecode;
        this.jsonEncode = jsonEncode;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline channelPipeline = socketChannel.pipeline();
        channelPipeline.addLast("decoder",jsonDecode);
        channelPipeline.addLast("encoder",jsonEncode);
        //空闲检测 读：5s 写：7s 读写：10s
        channelPipeline.addLast(new IdleStateHandler(5,7,3, TimeUnit.SECONDS));
        channelPipeline.addLast("handler",nettyHandler);
        // 如果后期处理拆包粘包可以在这里处理
        /** LineBasedFrameDecoder：以行为单位进行数据包的解码，使用换行符\n或者\r\n作为依据遇
             到\n或者\r\n都认为是一条完整的消息。
             DelimiterBasedFrameDecoder：以特殊的符号作为分隔来进行数据包的解码。
             FixedLengthFrameDecoder：以固定长度进行数据包的解码。
             LenghtFieldBasedFrameDecode：适用于消息头包含消息长度的协议（最常用）。
         */
//        channelPipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    }

}
